package ael.imarkket;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;

import ael.imarkket.Library.ConnectionChecking;
import ael.imarkket.Library.Constantes;
import ael.imarkket.Library.HttpPostGet;
import ael.imarkket.Library.HttpPostGet.RequestMethod;
import ael.imarkket.Library.Logging;
import ael.imarkket.Library.Preferencing;
import ael.imarkket.Library.StatusApp;
import android.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity which displays a login screen to the user, offering registration as well.
 */
public class Login extends Activity {

	static InputStream			is				= null;
	String						ResponseHTTP	= "";

	// Cambiar este dato a 5 o m�s y hacer que sea m�s complicada en base a lo
	// que est� puesto en el PHP.
	private static int			LENGTH_PASSWORD	= 2;

	Integer						ResultTask		= null;

	// Values for email and password at the time of the login attempt.
	private String				mEmail;
	private String				mPassword;
	private String				mRetypePassword;

	private int					pMODO;

	private SignInButton		btnSignIn;
	private PlusClient			plusClient;
	private ConnectionResult	connectionResult;

	// UI references.
	private EditText			mEmailView;
	private EditText			mPasswordView;
	private CheckBox			mCheckRemenberView;
	private CheckBox			mCheckAutoLogin;
	private EditText			mRetypePasswordView;
	private Button				mButtonRegister;
	protected LoginTask			_Task			= null;

	static Context				context;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.action_sign_exit));
			attemptExit();
			// Si el listener devuelve true, significa que el evento esta
			// procesado, y nadie debe hacer nada mas
			return true;
		}
		// para las demas cosas, se reenvia el evento al listener habitual
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_login, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.login_menu_exit:
				Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.action_sign_exit));
				attemptExit();
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}

	public void RecordarMailPassword() {

		Context context = getApplicationContext();
		Preferencing appPrefs = new Preferencing(context);

		if (mCheckRemenberView.isChecked()) {
			// Guardar preferencias
			appPrefs.setUsername(mEmailView.getText().toString());
			appPrefs.setPassword(mPasswordView.getText().toString());
			// Fin preferencias
			// Toast.makeText(LoginActivity.this, "Configuraci�n almacenada",
			// Toast.LENGTH_LONG).show();
		}

		// Siempre guardamos en la preferencia temporal el usuario y el nombre por si no se pincha en recordar tirar de esta preferencia
		appPrefs.setUsernameTemp(mEmailView.getText().toString());
		appPrefs.setPasswordTemp(mPasswordView.getText().toString());

		// Esta preferencia la guardamos siempre
		appPrefs.setCheckRemenberPref(mCheckRemenberView.isChecked());
		appPrefs.setAutoLogin(mCheckAutoLogin.isChecked());
	}

	/**
	 * Attempts to exit .
	 */
	public void attemptExit() {

		// 1. Instantiate an AlertDialog.Builder with its constructor
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		// 2. Chain together various setter methods to set the dialog
		// characteristics
		builder.setMessage(R.string.action_sign_exit_text).setTitle(R.string.action_sign_exit);

		builder.setPositiveButton(R.string.dialog_yes, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// User clicked OK button
				// Salimos de la herramienta
				Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.action_sign_exit) + "OK");

				// Si el check est� pinchado recordar en las preferences
				RecordarMailPassword();

				finish();
			}
		});

		builder.setNegativeButton(R.string.dialog_no, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// User cancelled the dialog
				// No hacemos nada
				Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.action_sign_exit) + "FAIL");
			}
		});

		// 3. Get the AlertDialog from create()
		AlertDialog dialog = builder.create();

		// Mostramos el cuadro de dialogo
		dialog.show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Inicializamos valores
		this.pMODO = R.string.label_LOGIN;

		// Inicializamos la tarea
		this.ResultTask = null;

		Logging.getInstance().log(Logging.LOG_INFO, getString(this.pMODO));

		setTitle(getString(R.string.app_name) + " - " + getString(R.string.label_LOGIN));

		setContentView(R.layout.activity_login);

		// Set up the login form.
		mEmailView = (EditText) findViewById(R.id.email);

		// Restauramos el email por defecto en las preferencias
		Context context = getApplicationContext();
		Preferencing appPrefs = new Preferencing(context);
		mEmailView.setText(appPrefs.getUsername(true));

		// Fin preferencias

		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
				if (id == R.id.login || id == EditorInfo.IME_NULL) {

					try {
						Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.action_sign_in) + ":" + mEmailView.getText() + "/" + mPasswordView.getText());
						attemptLogin();
					} catch (IOException e) {
						Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.action_sign_in) + ": (FAIL)" + mEmailView.getText() + "/" + mPasswordView.getText());
						e.printStackTrace();
					}
					return true;
				}
				return false;
			}
		});

		// Quitar esto
		mPasswordView.setText(appPrefs.getPassword(true));

		// Botón de login
		findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.action_sign_in) + ":" + mEmailView.getText() + "/" + mPasswordView.getText());
				try {
					attemptLogin();
				} catch (IOException e) {
					Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.action_sign_in) + ": (FAIL)" + mEmail + "/" + mPasswordView.getText());
					e.printStackTrace();
				}
			}
		});

		// Preferncia del check
		mCheckRemenberView = (CheckBox) findViewById(R.id.chk_remember);
		mCheckRemenberView.setChecked(appPrefs.getCheckRemenberPref());

		// Preferncia del login
		mCheckAutoLogin = (CheckBox) findViewById(R.id.chk_auto_login);
		mCheckAutoLogin.setChecked(appPrefs.getAutoLogin());

		// Si esta puesto que se auto-loguee, cargo el login
		if (appPrefs.getAutoLogin()) {
			try {
				attemptLogin();
			} catch (IOException e) {
				Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.action_auto_login) + ": FAIL");
				e.printStackTrace();
			}
		}

		findViewById(R.id.register_button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.action_register) + ":" + mEmailView.getText() + "/" + mPasswordView.getText());
				attemptRegister();
			}
		});

		mRetypePasswordView = (EditText) findViewById(R.id.retype_password);
		mRetypePasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
				if (id == R.id.login || id == EditorInfo.IME_NULL) {

					Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.action_register) + ":" + mEmailView.getText() + "/" + mPasswordView.getText());
					attemptRegister();
					return true;
				}
				return false;
			}
		});

		btnSignIn = (SignInButton) findViewById(R.id.sign_in_button_google);

		plusClient = new PlusClient.Builder(this, this, this).setVisibleActivities("http://schemas.google.com/AddActivity", "http://schemas.google.com/ListenActivity").build();

		connectionProgressDialog = new ProgressDialog(this);
		connectionProgressDialog.setMessage("Conectando...");

		btnSignIn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				if (!plusClient.isConnected()) {
					if (connectionResult == null) {
						connectionProgressDialog.show();
					} else {
						try {
							connectionResult.startResolutionForResult(MainActivity.this, REQUEST_CODE_RESOLVE_ERR);
						} catch (SendIntentException e) {
							connectionResult = null;
							plusClient.connect();
						}
					}
				}
			}
		});

	}

	public final static boolean isValidEmail(CharSequence target) {
		if (target == null) {
			return false;
		} else {
			return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
		}
	}

	public void attemptRegister() {

		// Si el check est� pinchado recordar en las preferences
		RecordarMailPassword();

		mRetypePasswordView = (EditText) findViewById(R.id.retype_password);
		mButtonRegister = (Button) findViewById(R.id.register_button);

		if (mRetypePasswordView.getVisibility() == View.VISIBLE) {

			boolean cancel = false;
			View focusView = null;

			// Reset errors.
			mEmailView.setError(null);
			mPasswordView.setError(null);
			mRetypePasswordView.setError(null);

			// Store values at the time of the login attempt.
			mEmail = mEmailView.getText().toString();
			mPassword = mPasswordView.getText().toString();
			mRetypePassword = mRetypePasswordView.getText().toString();

			// Check for a valid password.
			if (TextUtils.isEmpty(mPassword)) {
				mPasswordView.setError(getString(R.string.error_field_required));
				focusView = mPasswordView;
				cancel = true;
			} else if (TextUtils.isEmpty(mRetypePassword)) {
				mRetypePasswordView.setError(getString(R.string.error_field_required));
				focusView = mRetypePasswordView;
				cancel = true;
			} else if (mPassword.length() < Login.LENGTH_PASSWORD) {
				mPasswordView.setError(getString(R.string.error_invalid_password));
				focusView = mPasswordView;
				cancel = true;
			} else if (mRetypePassword.length() < Login.LENGTH_PASSWORD) {
				mRetypePasswordView.setError(getString(R.string.error_invalid_password));
				focusView = mRetypePasswordView;
				cancel = true;
			}

			// mPasswordView.setError("*" + mRetypePassword + "-" + mPassword + "*");
			// Check for a valid email address.
			if (TextUtils.isEmpty(mEmail)) {
				mEmailView.setError(getString(R.string.error_field_required));
				focusView = mEmailView;
				cancel = true;
			} else if (!mEmail.contains("@")) {
				mEmailView.setError(getString(R.string.error_invalid_email));
				focusView = mEmailView;
				cancel = true;
			} else if (!isValidEmail(mEmail)) {
				mEmailView.setError(getString(R.string.VALIDATION_EMAIL_ERROR));
				focusView = mEmailView;
				cancel = true;
			} else if (!mPassword.equals(mRetypePassword)) {
				mPasswordView.setError(getString(R.string.VALIDATION_PASSWORD_DISTINTAS));
				focusView = mPasswordView;
				cancel = true;
			}

			if (cancel) {
				// There was an error; don't attempt login and focus the first
				// form field with an error.
				focusView.requestFocus();
				Logging.getInstance().log(Logging.LOG_INFO, "Cancelado");
			} else {
				// Show a progress spinner, and kick off a background task to
				// perform the user login attempt.
				CargarLoginTask(context, getString(R.string.AppCheckConnection_thinking), getString(R.string.STR_OPERATION_REGISTER_USER));
			}

		} else {
			mRetypePasswordView.setVisibility(View.VISIBLE);
			mButtonRegister.setText(R.string.action_nuevo);
		}
	}

	public void attemptLogin() throws IOException {

		// Quitamos los campos de registro de usuario
		mRetypePasswordView = (EditText) findViewById(R.id.retype_password);
		mButtonRegister = (Button) findViewById(R.id.register_button);

		mRetypePasswordView.setVisibility(View.INVISIBLE);
		mButtonRegister.setText(R.string.action_register);

		// Si el check est� pinchado recordar en las preferences
		RecordarMailPassword();

		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < Login.LENGTH_PASSWORD) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		} else if (!mEmail.contains("@")) {
			mEmailView.setError(getString(R.string.error_invalid_email));
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.

			Logging.getInstance().log(Logging.LOG_INFO, "Lanzamos InitTask");
			CargarLoginTask(context, getString(R.string.AppCheckConnection_thinking), getString(R.string.STR_OPERATION_LOGIN));
		}
	}

	private void CargarLoginTask(Context context, String str_modo, String modo) {
		// Lanzamos la tarea asíncrona
		// Lanzar la ejecución solo una vez
		if (_Task != null && _Task.getStatus() != AsyncTask.Status.FINISHED) {
			Logging.getInstance().log(Logging.LOG_INFO, "Cancelando CloseSessionTask (si existe antes)");
			_Task.cancel(true);
		}

		// ///////// TAREA ASINCRONA
		_Task = new LoginTask(Login.this, str_modo, modo);
		_Task.execute(this);

		try {
			this.ResultTask = _Task.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	/*
	 * TAREA LOGIN ASINCRONA
	 */
	protected class LoginTask extends AsyncTask<Context, Integer, Integer> {

		Context						context;
		String						str_mesg;
		String						modo;
		ProgressDialog				progress;

		private static final int	NETWORK_THINKING							= 0;

		private static final int	NETWORK_OK									= 1;
		private static final int	NETWORK_FAIL								= 2;
		private static final int	NETWORK_WIFI								= 3;
		private static final int	NETWORK_MOBILE								= 4;
		private static final int	NETWORK_UNKNOWN								= 5;

		private static final int	CONNECTING_TO_SERVER						= 6;
		private static final int	CONNECTING_TO_SERVER_OK						= 7;
		private static final int	CONNECTING_TO_SERVER_ERROR					= 8;
		private static final int	CONNECTING_TO_SERVER_FINISH					= 9;
		private static final int	HTTP_CONNECTING_ERROR						= 10;
		private static final int	CONNECTING_TO_SERVER_ERROR_SOCKETTIMEOUT	= 11;
		private static final int	CONNECTING_TO_SERVER_ERROR_PROTOCOL			= 12;

		public LoginTask(Context context, String str_modo, String modo) {
			Logging.getInstance().log(Logging.LOG_INFO, "CONSTRUCTOR");
			this.context = context;
			this.str_mesg = str_modo;
			this.modo = modo;
		}

		// -- run intensive processes here
		// -- notice that the datatype of the first param in the class
		// definition matches the param passed to this method
		// -- and that the datatype of the last param in the class definition
		// matches the return type of this mehtod
		@Override
		protected Integer doInBackground(Context... params) {
			// -- on every iteration
			// -- runs a while loop that causes the thread to sleep for 50
			// milliseconds
			// -- publishes the progress - calls the onProgressUpdate handler
			// defined below
			// -- and increments the counter variable i by one
			/*
			 * int i = 0; while (i <= 50) { try { Thread.sleep(50); publishProgress(i); i++; } catch (Exception e) { Logging.getInstance().log( "[doInBackground]" +
			 * e.getMessage()); } }
			 */
			// Variable de retorno de la tarea as�ncrona
			// 1 si hay error
			// 0 si ha ido todo bien
			Integer return_code = 1;

			publishProgress(NETWORK_THINKING);

			// Comprobamos si hay conexion
			if (StatusApp.getInstance(this.context).isOnline(context)) {
				publishProgress(NETWORK_OK);
				Logging.getInstance().log(Logging.LOG_INFO, StatusApp.getInstance(this.context).getTypeStatus());

				// Comprobamos si es por wifi o mobil
				if ((ConnectionChecking.getInstance(this.context).CheckWIFI()) || (ConnectionChecking.getInstance(this.context).CheckMOBILE())) {
					if (ConnectionChecking.getInstance(this.context).CheckWIFI()) {
						publishProgress(NETWORK_WIFI);
					} else if (ConnectionChecking.getInstance(this.context).CheckMOBILE()) {
						publishProgress(NETWORK_MOBILE);
					}
					// Si llega aqu� todo va bien lanzamos la conexion http
					// ****************************************************
					try {
						// Conexion http
						// Probamos la conexion contra el servidor para ver si
						// hay respuesta si nos devuelve 0 est� ok si nos
						// devuelve otra cosa distinta de 0
						// no hay conexi�n con el servidor.

						publishProgress(CONNECTING_TO_SERVER);
						Constantes Constantes = new Constantes();

						HttpPostGet client = new HttpPostGet(Constantes.getAPI_PROTOCOL_HTTP() + Constantes.getAPI_IP(Constantes.getModoIP()) + Constantes.getAPI_URL_BASE()
								+ Constantes.getAPI_FILE(), Constantes.getAPI_CODIFICACION(), Constantes.getID_APP());

						/*
						 * Creamos el array con los datos de la operacion, username y password
						 */
						ArrayList<NameValuePair> OpeUserPassw = new ArrayList<NameValuePair>();
						OpeUserPassw.add(new BasicNameValuePair(getString(R.string.STR_OPERATION), this.modo));

						// Consultar las preferencias
						Context context = getApplicationContext();
						Preferencing appPrefs = new Preferencing(context);

						// Parámetros
						OpeUserPassw.add(new BasicNameValuePair(getString(R.string.STR_USERNAME), appPrefs.getUsername(false)));
						OpeUserPassw.add(new BasicNameValuePair(getString(R.string.STR_PASSWORD), appPrefs.getPassword(false)));

						try {
							// Le pasamos el array con las operaciones y los
							// datos del usuario
							// La variable HTTP_USER_AGENT_APP_ANDROID es para
							// que el php que detecta el movil lo ponga como
							// APP_MOVIL
							client.Execute(RequestMethod.POST, getString(R.string.HTTP_USER_AGENT_APP_ANDROID), OpeUserPassw, this.context, this.modo);
							publishProgress(CONNECTING_TO_SERVER_OK);
						} catch (SocketTimeoutException e) {
							publishProgress(CONNECTING_TO_SERVER_ERROR_SOCKETTIMEOUT);
							Logging.getInstance().log(Logging.LOG_ERROR, e.toString());
						} catch (ClientProtocolException e) {
							publishProgress(CONNECTING_TO_SERVER_ERROR_PROTOCOL);
							Logging.getInstance().log(Logging.LOG_ERROR, e.toString());
						} catch (Exception e) {
							Logging.getInstance().log(Logging.LOG_ERROR, e.toString());
							publishProgress(CONNECTING_TO_SERVER_ERROR);
						}

						// Guardamos la respuesta de la petici�n HTTP.
						ResponseHTTP = client.getResponse();
						ResponseHTTP = ResponseHTTP.replaceAll("[\n\r]", "");
						ResponseHTTP = ResponseHTTP.trim();
						int responseCode = client.getResponseCode();
						Logging.getInstance().log(Logging.LOG_INFO, "ResponseHTTP:  " + ResponseHTTP);
						Logging.getInstance().log(Logging.LOG_INFO, "ResponseCODE:  " + responseCode);
						// 200
						if (responseCode == HttpStatus.SC_OK) {
							publishProgress(CONNECTING_TO_SERVER_FINISH);
							return_code = 0;
						} else {
							// Hago esto para que si hay alg�n error me lo
							// devuelve en un Toast
							publishProgress(responseCode);
						}

						// Fin conexion http
					} catch (Exception e) {
						Logging.getInstance().log(Logging.LOG_ERROR, e.toString());
						publishProgress(HTTP_CONNECTING_ERROR);
					}
					// ****************************************************
				} else {
					// ni wifi ni mobile
					publishProgress(NETWORK_UNKNOWN);
				}
			} else {
				// sin conexion
				publishProgress(NETWORK_FAIL);
			}
			// Variable de retorno de la tarea as�ncrona
			// 1 -> si devuelve 1 es que no se ha realizado correctamente la
			// conexi�n. Despu�s tenemos que procesar el resultado json.
			return return_code;
		}

		// -- gets called just before thread begins
		@Override
		protected void onPreExecute() {
			Logging.getInstance().log(Logging.LOG_INFO, "INICIALIZANDO");
			super.onPreExecute();

			progress = new ProgressDialog(context);
			progress.setMessage(str_mesg);
			// set other progressbar attributes
			progress.show();
		}

		// -- called from the publish progress
		// -- notice that the datatype of the second param gets passed to this
		// method
		@Override
		protected void onProgressUpdate(Integer... code) {
			super.onProgressUpdate(code);

			String mensaje = "";
			switch (code[0]) {
				case NETWORK_OK:
					mensaje = getString(R.string.AppCheckConnection_ok);
					break;
				case NETWORK_FAIL:
					mensaje = getString(R.string.AppCheckConnection_fail);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case NETWORK_WIFI:
					mensaje = getString(R.string.AppCheckConnection_ok) + " " + getString(R.string.AppCheckConnection_wifi_connection);
					break;
				case NETWORK_MOBILE:
					mensaje = getString(R.string.AppCheckConnection_ok) + " " + getString(R.string.AppCheckConnection_mobile_connection);
					break;
				case NETWORK_UNKNOWN:
					mensaje = getString(R.string.AppCheckConnection_ok) + " " + getString(R.string.AppCheckConnection_unknown);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case CONNECTING_TO_SERVER:
					mensaje = getString(R.string.Connect_to_server);
					break;
				case CONNECTING_TO_SERVER_OK:
					mensaje = getString(R.string.Connect_to_server) + " " + getString(R.string.Connect_to_server_ok);
					break;
				case CONNECTING_TO_SERVER_ERROR:
					mensaje = getString(R.string.Connect_to_server) + " " + getString(R.string.Connect_to_server_error_refused);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case CONNECTING_TO_SERVER_FINISH:
					// mensaje = getString(R.string.Connect_to_server) + " " +
					// getString(R.string.Connect_to_server_ok);
					// Toast.makeText(getApplicationContext(),
					// getString(R.string.Http_Connect_Finish),
					// Toast.LENGTH_LONG).show();
					break;
				case HTTP_CONNECTING_ERROR:
					mensaje = getString(R.string.Http_Connect_Error);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case CONNECTING_TO_SERVER_ERROR_SOCKETTIMEOUT:
					mensaje = getString(R.string.Connect_to_server_error_sockettimeout);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case CONNECTING_TO_SERVER_ERROR_PROTOCOL:
					mensaje = getString(R.string.Connect_to_server_error_protocol);
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
				case NETWORK_THINKING:
					mensaje = getString(R.string.AppCheckConnection_thinking);
					break;
				default:
					// Aqu� se va cuando hay mensajes 200, 300, 400, ... 500 ....
					mensaje = getString(R.string.Connect_to_server) + " - ErrorCode:" + code[0].toString();
					Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_LONG).show();
					break;
			}
			Logging.getInstance().log(Logging.LOG_INFO, "PROGRESS: (" + code[0].toString() + ")" + mensaje);
			progress.setMessage(mensaje);
			// Hacemos una pausa peque�a
			// SystemClock.sleep(100);

		}

		// -- called if the cancel button is pressed
		@Override
		protected void onCancelled() {
			super.onCancelled();
			Logging.getInstance().log(Logging.LOG_INFO, "CANCELLED");
		}

		// -- called as soon as doInBackground method completes
		// -- notice that the third param gets passed to this method
		@Override
		protected void onPostExecute(Integer result) {

			// result = 1 error
			// result = 0 ok
			Logging.getInstance().log(Logging.LOG_INFO, "1Result:  " + result + " ResponseHTTP: " + ResponseHTTP);

			// La conexion se ha realiado con �xito ahora hay que ver si el
			// login se ha hecho bien.
			if (result == 0) {
				// Comprobamos el json
				if ((ResponseHTTP == "") || (ResponseHTTP == null)) {
					Toast.makeText(getApplicationContext(), getString(R.string.LOGIN_ERROR) + ':' + this.modo, Toast.LENGTH_LONG).show();
					Logging.getInstance()
							.log(Logging.LOG_INFO, getString(R.string.LOGIN_ERROR) + ':' + this.modo + ' ' + " 2Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
				} else {
					if (this.modo == getString(R.string.STR_OPERATION_LOGIN)) {
						Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.STR_OPERATION_LOGIN));
						// login
						// ResponseHTTP:
						// -1 -> YA ESTOY LOGUEADO
						// 0 -> ERROR EN PROCESO PROCESO_Login o SESSION_PROCESO_Login
						// 3 -> USUARIO ACTIVO EN OTRO EQUIPO
						// 4 -> USUARIO INACTIVO ANTES DE LOGUEARSE
						// 5 -> USUARIO BLOQUEADO
						// 6 -> USUARIO en PENDING_ACTIVATE
						// El login solo se produce en los estados 3 o 4 en la web y
						// en los estado 3, 4 y -1 en APP ya que si estoy logueado como u1
						// por la web y me logueo por la APP me debe de dejar

						if (ResponseHTTP.equals("0")) {
							Toast.makeText(getApplicationContext(), getString(R.string.LOGIN_ERROR), Toast.LENGTH_LONG).show();
							Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.LOGIN_ERROR) + " 3Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
						} else if (ResponseHTTP.equals("5")) {
							Toast.makeText(getApplicationContext(), getString(R.string.LOGIN_BLOCKED), Toast.LENGTH_LONG).show();
							Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.LOGIN_BLOCKED) + " 4Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
						} else if (ResponseHTTP.equals("6")) {
							Toast.makeText(getApplicationContext(), getString(R.string.LOGIN_PENDING_ACTIVATE), Toast.LENGTH_LONG).show();
							Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.LOGIN_PENDING_ACTIVATE) + " 4Result:  " + result + " ResponseHTTP: " + ResponseHTTP);

						} else if ((ResponseHTTP.equals("-1")) || (ResponseHTTP.equals("3")) || (ResponseHTTP.equals("4"))) {
							Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.LOGIN_OK) + " 5Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
							Intent mainIntent = new Intent().setClass(Login.this, ShoppingList.class);
							startActivity(mainIntent);
							finish();
						} else {
							Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.LOGIN_ERROR) + " 6Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
						}
					} else if (this.modo == getString(R.string.STR_OPERATION_REGISTER_USER)) {
						// crar nuevo usuario
						Logging.getInstance().log(Logging.LOG_INFO, getString(R.string.STR_OPERATION_REGISTER_USER));
						// Al crear el nuevo usuario
						// Result = 0 y ResponseHTTP = 0
						// Si hay error
						// Result = 0 y ResponseHTTP > 0, por ejemplo 1, es un usuario con ese nombre de usuario
						if (ResponseHTTP.equals("0")) {
							Toast.makeText(getApplicationContext(), getString(R.string.register_ok), Toast.LENGTH_LONG).show();
							Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.register_ok) + " 3Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
						} else if (ResponseHTTP.equals("1")) {
							Toast.makeText(getApplicationContext(), getString(R.string.register_fail_yaexiste), Toast.LENGTH_LONG).show();
							Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.register_fail_yaexiste) + " 4Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
						} else if (ResponseHTTP.equals("6")) {
							Toast.makeText(getApplicationContext(), getString(R.string.LOGIN_PENDING_ACTIVATE), Toast.LENGTH_LONG).show();
							Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.LOGIN_PENDING_ACTIVATE) + " 4Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
						}
					}
				}

			} else if (result == 1) {
				Toast.makeText(getApplicationContext(), getString(R.string.LOGIN_ERROR), Toast.LENGTH_LONG).show();
				Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.LOGIN_ERROR) + " 7Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
			} else {
				Toast.makeText(getApplicationContext(), getString(R.string.LOGIN_UNKNOWN) + result.toString(), Toast.LENGTH_LONG).show();
				Logging.getInstance().log(Logging.LOG_ERROR, getString(R.string.LOGIN_UNKNOWN) + " 8Result:  " + result + " ResponseHTTP: " + ResponseHTTP);
			}

			progress.dismiss();
		}

	}

	/*
	 * FIN TAREA LOGIN ASINCRONA
	 */

}